package sseGameApps.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sseGameApps.service.AuthService;

public class AuthFilter implements Filter {

    private AuthService service = new AuthService();

    public void doFilter(ServletRequest request, ServletResponse response,
             FilterChain filterChain) throws IOException, ServletException {

    // session
    HttpSession session = ((HttpServletRequest)request).getSession();
    if (session.getAttribute("userId") == null){
        ((HttpServletResponse)response).sendRedirect("/");
        return;
    }

    // 
    Date now = new Date(System.currentTimeMillis());

    // JST ��
    TimeZone tz = TimeZone.getTimeZone("JST");
    SimpleDateFormat df =
        new SimpleDateFormat("yyyy/MM/dd HH:mm:ss",request.getLocale());
    df.setTimeZone(tz);

//    if (!service.verifyAuth(request.getParameter("userId"), df.format(now), request.getLocale())) {
    if (!service.verifyAuth(session.getAttribute("userId").toString(), df.format(now), request.getLocale())) {
        ((HttpServletResponse)response).sendRedirect("/");
        return;
    }

    // 
    filterChain.doFilter(request, response);

  }

  public void destroy() {
  }

  public void init(FilterConfig arg0) throws ServletException {
  }

}